package cn.cvs.controller;

import cn.cvs.pojo.SysUser;
import cn.cvs.service.sysUser.SysUserService;
import cn.cvs.utils.Constants;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class SysUserController {
	private Logger logger = Logger.getLogger(SysUserController.class);
	@RequestMapping("/hello")
	public String welcome(String realName){
		logger.info("欢迎使用Spring MVC, realName:" + realName);
		return "index";
	}
	@Resource
	private SysUserService sysUserService;

	/**
	 * 跳转到登录页面
	 * @return
	 */
	@RequestMapping(value="/toLogin")
	public String login(){
		logger.debug("跳转到登录页面");
		return "login";
	}

	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String doLogin(@RequestParam String account, @RequestParam String password, HttpServletRequest request, HttpSession session){
		logger.debug("登录方法");
		//调用service方法，进行用户匹配
		SysUser sysUser = sysUserService.login(account,password);
		if(null != sysUser){//登录成功
			//放入session
			session.setAttribute(Constants.USER_SESSION, sysUser);
			return "redirect:/user/toMain";
			//response.sendRedirect("jsp/frame.jsp");
		}else{
			//页面跳转（login.jsp）带出提示信息--转发
			request.setAttribute("error", "用户名或密码不正确");
			return "login";
		}
	}
	@RequestMapping(value="/toMain")
	public String main(HttpSession session){
		if(session.getAttribute(Constants.USER_SESSION) == null){
			//重定向到登录页面接口
			return "redirect:/user/toLogin";
		}
		return "frame";
	}

	/**
	 * 一个抛出异常的接口
	 * @param account
	 * @param password
	 * @return
	 */
	@RequestMapping("/exLogin")
	public String exLogin(String account, String password){
		logger.debug("一个抛出异常的接口");
		//调用service方法，进行用户匹配
		SysUser user = sysUserService.login(account,password);
		if(null == user){//登录失败
			throw new NullPointerException("空指针异常！");
		}else{
			throw new RuntimeException("用户名或者密码不正确，跳转到错误页面！");
		}
//		return "redirect:/user/toMain";
	}

	/**
	 * 捕获异常信息，跳转到error页面
	 * @param e
	 * @param req
	 * @return
	 */
	@ExceptionHandler(value={Exception.class})
	public String handlerException(Exception e, HttpServletRequest req){
		req.setAttribute("e", e);
		return "error";
	}
}
